<?php
    @header("Content-Type:text/html;charset=utf-8");

    @include_once("conn.php");   // 引入conn.php (链接mysql)
    @include_once("common.php");

    if(!(isset($_POST["username"])&&isset($_POST["pid"])&&isset($_POST["buyNum"]))){
        paramsErr();
    }

    $username = $_POST["username"];
    $pid = $_POST["pid"];
    $buyNum = $_POST["buyNum"];
   
    $sql = "select * from `cart` where username='$username' and pid ='$pid'";
    $result = mysqli_query($conn,$sql);

    $obj = array();
    if($result){ 
        $item = mysqli_fetch_assoc($result);//如果有结果 查到了update
        if($item){
            $sql = "update `cart` set buyNum = buyNum + $buyNum  where username = '$username' and pid = '$pid'";
        }else{
            $sql = "insert into `cart`(username,pid,buyNum) values('$username','$pid','$buyNum')";
        }
        $result = mysqli_query($conn,$sql);
        $obj = array();
        if($result){ 
            $rows = mysqli_affected_rows($conn);// > 0 的整数表示所影响的记录行数。0 表示没有受影响的记录。-1 表示查询返回错误。
            if($rows > 0){
                $obj["status"] = true;
                $obj["msg"] = "加入成功";
            }else{  // 加入不会出现此情况
                $obj["status"] = false;
                $obj["msg"] = "加入失败,数据未改变";
            }
        }else{
            $obj["status"] = false;
            $obj["msg"] = "sql语句有误";
            $obj["sql"] = $sql;
        }

    }else{
        $obj["status"] = false;
        $obj["msg"] = "sql语句有误";
        $obj["sql"] = $sql;
    }


   
    echo json_encode($obj);
?>